package leetcodev1.树;

import leetcodev1.链表.Solution;

public class LeetCode129 {

    public int sumNumbers(TreeNode root) {
        if (root == null) {
            return 0;
        }

        if (root.left == null && root.right == null) {
            return root.val;
        }

        if (root.left == null) {
            return root.val + sumNumbers(root.right) + 10 * root.val;
        }

        if (root.right == null) {
            return root.val + sumNumbers(root.left) + 10 * root.val;
        }

        return sumNumbers(root.left) + sumNumbers(root.right) + 20 * root.val;
    }
}

class Answer129 {
    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }

    public int dfs(TreeNode root, int prevSum) {
        if (root == null) {
            return 0;
        }
        int sum = prevSum * 10 + root.val;
        if (root.left == null && root.right == null) {
            return sum;
        } else {
            return dfs(root.left, sum) + dfs(root.right, sum);
        }
    }
}
